using System;
using Amazon.ECS.Model;
using RomanJendrusz.Amazon.ETL.Domain;
using RomanJendrusz.Amazon.ETL.Infrastructure;
using Customer=RomanJendrusz.Amazon.ETL.Domain.Customer;
using System.Collections.Generic;
using RomanJendrusz.Amazon.ETL.Infrastructure.Loging.Core;

namespace RomanJendrusz.Amazon.ETL.Messages.MessageMappers
{
    public class GetBookReviewsMapper: MessageMapper<GetBookReviewsRequest, ItemLookupRequest, ItemLookupResponse>
    {
        public override AmazonResponse MapToAmazonResponse(ItemLookupResponse awsResponse)
        {
            var bookItem = GetRequestItem(awsResponse, 0);
            if(bookItem.IsSetCustomerReviews()== false)
            {
                LogGateway.LogFor(GetType()).Error("The request doesn't have any customer reviews" );
                return new GetBookReviewsResponse(CorrelationId) {Reviews = new List<CustomerReview>()};
            }
            var response = new GetBookReviewsResponse(CorrelationId);
            var reviews = new List<CustomerReview>();
            foreach (var review in bookItem.CustomerReviews.Review)
            {
                var customerReview = new CustomerReview();
                customerReview.AddedDate = Convert.ToDateTime(AssertThat.IsNotNull(review.Date, "AddedDate"));
                customerReview.Content = AssertThat.IsNotNull(review.Content, "Content");
                customerReview.HelpfulVotes = Convert.ToInt32(review.HelpfulVotes);
                customerReview.Rating = Convert.ToInt16((review.Rating));
                customerReview.Summary = AssertThat.IsNotNull(review.Summary, "Summary");
                customerReview.TotalVotes = Convert.ToInt32(review.TotalVotes);
                var reviewer = review.Reviewer;
                if (reviewer != null)
                {
                    customerReview.Customer = new Customer
                    {
                        CustomerId =
                            AssertThat.IsNotNull(reviewer.CustomerId, "CustomerId"),
                        CustomerName = reviewer.Name,
                        Nickname = reviewer.Nickname,
                        Location = reviewer.Location,
                    };
                }
                reviews.Add(customerReview);
            }
            response.Reviews = reviews;
            return response;
        }

        public override ItemLookupRequest MapToAwsRequest(GetBookReviewsRequest request)
        {
            var awsRequest = new ItemLookupRequest { MerchantId = request.MerchantId };
            awsRequest.ItemId.Add(request.BookAsin);
            //awsRequest.IdType = "ISBN";
            //awsRequest.SearchIndex = "Books";
            awsRequest.ReviewPage = request.PageNumber;
            awsRequest.ResponseGroup.Add(request.ResponseGroup);
            awsRequest.MerchantId = request.MerchantId;
            return awsRequest;
        }
    }
}